﻿using TuLing.Blazor.Dto;
using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public interface ISaleOrderService
    {
        void Delete(long id);
        SaleOrder? Get(long id);
        void LoadData(SaleOrder order);
        SaleOrder Save(SaleOrder order);
        List<SaleOrder> Search(BaseInput input);
    }

    public class SaleOrderService : BaseService, ISaleOrderService
    {
        public SaleOrderService(DefaultDbContext context) : base(context) { }

        public List<SaleOrder> Search(BaseInput input)
        {
            return _context.SaleOrders.ToList();
        }
        
        public SaleOrder? Get(long id)
        {
            return _context.SaleOrders.FirstOrDefault(m => m.Id == id);
        }

        public void LoadData(SaleOrder order)
        {            
            if (order == null) return;
            _context.Entry(order).State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
            _context.Entry(order).Collection(o => o.Details).Load();
            _context.Entry(order).Reference(o => o.Customer).Load();
            foreach (var detail in order.Details)
            {
                _context.Entry(detail).Reference(d => d.Product).Load();
            }
        }


        public SaleOrder Save(SaleOrder order)
        {
            if (order.Id == 0)
            {
                _context.SaleOrders.Add(order);
            }
            _context.SaveChanges();
            return order;
        }

        public void Delete(long id)
        {
            try
            {
                var oldOrder = _context.SaleOrders.Where(m => m.Id == id).FirstOrDefault();
                if (oldOrder == null)
                {
                    throw new Exception("没找到销售单");
                }
                _context.SaleOrders.Remove(oldOrder);
                _context.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}
